package com.ibiz.znjd.plugin;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.getcapacitor.JSObject;
import com.getcapacitor.NativePlugin;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.ibiz.znjd.MainActivity;
import com.ibiz.znjd.MainApplication;
import com.ibiz.znjd.baidu.location.LocationService;
import com.ibiz.znjd.baidu.location.LocationServiceListener;

@NativePlugin()
public class LocationPlugin extends Plugin {
    /**
     * 定位服务
     */
    private LocationService locationService;

    /**
     * 是否输出后台定时定位的消息
     */
    public Boolean showBackNotify = false;

    /**
     * 定位服务监听器
     */
    private LocationServiceListener locationServiceListener = new LocationServiceListener() {
        @Override
        public void onReceiveLocation(BDLocation var1, JSObject locationObj) {
            if(showBackNotify){
                Toast.makeText(getContext(), locationObj.toString(), Toast.LENGTH_SHORT).show();
            }
//            GjInternal.testAlive("定位插件+定位回调");
            System.out.println("locationObj"+locationObj.toString());
            notifyListeners("onReceiveLocation", locationObj);
        }
    };

    @Override
    public void load(){
        // 获取定位服务
        locationService = ((MainApplication)(((MainActivity)getContext()).getApplication())).getLocationService();
        locationService.registerListener(locationServiceListener);
    }

    @PluginMethod()
    public void getLocation(PluginCall call) {
        String value = call.getString("value");
//        Toast.makeText(getContext(), ""+value, Toast.LENGTH_SHORT).show();
//        JSObject ret = new JSObject();
        JSObject locationObj = locationService.locationObj;
        call.resolve(locationObj);
    }

    @PluginMethod()
    public void checkAlive(PluginCall call) {
        String value = call.getString("time");
        Toast.makeText(getContext(), ""+value, Toast.LENGTH_SHORT).show();
//        JSObject ret = new JSObject();
//        JSObject locationObj = locationService.locationObj;
//        call.resolve(locationObj);
    }

    /**
     * 是否输出后台定时定位的消息的开关
     * @param call
     */
    @PluginMethod()
    public void triggerShowBackNotify(PluginCall call) {
        JSObject ret = new JSObject();
        if(call.hasOption("isShow")){
            Boolean isShow = call.getBoolean("isShow");
            showBackNotify = isShow instanceof Boolean ? isShow : !showBackNotify ;
        }else{
            showBackNotify = !showBackNotify;
        }
        ret.put("isShow", showBackNotify);
        call.resolve(ret);
    }


}
